package com.cattsoft.mobile.android.browser.javascript.run.lightdb;

import org.json.JSONArray;

import com.cattsoft.mobile.android.browser.ProgressUtil;
import com.cattsoft.mobile.android.browser.javascript.run.JsExtRunner;
import com.cattsoft.mobile.android.browser.util.JsRunHelper;
import com.cattsoft.mobile.android.db.sqlite.DBInstance;
import com.cattsoft.mobile.android.db.sqlite.SQLHelper;
import com.cattsoft.mobile.android.pub.StringUtil;

public class SQLBlockExecuteRunner extends JsExtRunner {
    private String sqlJSONArray;

    private String sucessCallBack;

    private String fatalCallBack;

    private DBInstance instance;

    public SQLBlockExecuteRunner(DBInstance instance, String sqlJSONArray, String sucessCallBack,
            String fatalCallBack) {
        super();
        this.instance = instance;
        this.sqlJSONArray = sqlJSONArray;
        this.sucessCallBack = sucessCallBack;
        this.fatalCallBack = fatalCallBack;
    }

    @Override
    public void run() {
        try {
            this.instance.beginTransaction();
            JSONArray blockResult = new JSONArray();
            JSONArray sqlBlock = new JSONArray(sqlJSONArray);
            if (sqlBlock.length() > 0) {
                for (int i = 0; i < sqlBlock.length(); i++) {
                    String sqlStatement = sqlBlock.getString(i);
                    if (StringUtil.isBlank(sqlStatement)) {
                        continue;
                    }
                    if (SQLHelper.isQueryStatement(sqlStatement)) {
                        JSONArray result = this.instance.query(sqlStatement);
                        blockResult.put(result);
                    } else {
                        this.instance.executeSQL(sqlStatement);
                        blockResult.put(true);
                    }
                }
                this.instance.commit();
            }
            if (!StringUtil.isBlank(sucessCallBack)) {
                JsRunHelper helper = new JsRunHelper();
                helper.appendJs(sucessCallBack + "(\""
                        + JsRunHelper.formatJsStringArg(blockResult.toString()) + "\");");
                this.webview.loadUrl(helper.prepareRun());
            }
        } catch (Throwable t) {
            if (!StringUtil.isBlank(fatalCallBack)) {
                JsRunHelper helper = new JsRunHelper();
                helper.appendJs(fatalCallBack + "(\"" + JsRunHelper.formatJsStringArg(t.toString())
                        + "\");");
                this.webview.loadUrl(helper.prepareRun());
            }
        } finally {
            this.instance.endTransaction();
            ProgressUtil.close();
        }
    }

}
